package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.bean.search.rule.Rule;
import com.fz.us.admin.base.bean.search.rule.RuleHelper;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.Remind;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.RemindService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.oa.core.entity.com.Task;
import com.fz.us.oa.core.entity.com.TaskFeedback;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.TaskFeedbackService;
import com.fz.us.oa.core.service.com.TaskService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/25.
 */
@Controller
@RequestMapping(value = "/com/taskfeedback")
public class TaskFeedbackController extends BaseController {
    private static final long serialVersionUID = 8927902750995667440L;

    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskFeedbackService taskFeedbackService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private FileManagerService fileManagerService;
    @Autowired
    private RemindService remindService;

    /**
     * 新建页面
     */
    @RequestMapping(value = "create/{taskId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String create(@CurrentUser User user, @PathVariable String taskId, Model model) {
        model.addAttribute("user",user);
        model.addAttribute("taskId",taskId);
        return "/com/taskfeedback_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model, @PathVariable String keyId) {

        TaskFeedback taskFeedback = taskFeedbackService.get(keyId);
        model.addAttribute("keyId", keyId);
        model.addAttribute("taskFeedback",taskFeedback);
        model.addAttribute("user",user);

        String fileId="";
        if(taskFeedback.getFile()!=null&&taskFeedback.getFile().size()>0){
            for(FileManage file:taskFeedback.getFile()){
                fileId+=file.getId()+",";
            }
        }
        model.addAttribute("fileId",fileId);

        String level = "部分完成";
        if(taskFeedback.getCompleteLevel()==1){
            level = "全部完成";
        }

        model.addAttribute("level",level);
        return "/com/taskfeedback_read";
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String taskId, String completeLevel, String feedbackContent, String fileIds) {

        Task task = taskService.get(taskId);

        if(task == null){
            return ajaxJson(resultService.fail("任务数据已丢失！"));
        }

        TaskFeedback taskFeedback = new TaskFeedback();
        taskFeedback.setTask(task);

        if (StringUtils.isNotBlank(completeLevel)) {
            int level = Integer.valueOf(completeLevel);
            taskFeedback.setCompleteLevel(level);

            //选择全部完成后，任务自动将状态变为“完成待验收”
            if (level==1) {
                task.setTxtStatus("完成待验收");
                taskService.update(task);

                //发送提醒
                Remind remind = new Remind();
                remind.setUser(task.getCreater());
                remind.setBussinessKey("task");
                remind.setKeyId(task.getId());
                remind.setContent(task.getName()+" 任务已完成，等待验收");
                remindService.save(remind);

            }
        }

        if (StringUtils.isNotBlank(feedbackContent)) {
            taskFeedback.setFeedbackContent(feedbackContent);
        }

        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        taskFeedback.setFile(fileManageList);

        taskFeedback.setCreater(user);
        taskFeedback.setCompany(user.getCompany());
        taskFeedback.setName(user.getName());

        return ajaxJson(taskFeedbackService.saveEntity(taskFeedback));
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,
                                            @RequestParam() String taskId,
                                            JqGridPager pager){
        Company company = user.getCompany();
        // 排序
        Order order =  Order.order("createTime", SearchEnum.OrderType.desc);
        SearchResultPaging searchResult = null;

        List<Rule> rules = new ArrayList<Rule>();
        rules.add(RuleHelper.eq("company", company));   // 所在的公司
        rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));    // 文档为有效的
        rules.add(RuleHelper.eq("task.id", taskId));

        searchResult = taskFeedbackService.findPagingBySearch(null, rules, order);

        List<TaskFeedback> taskFeedbackList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(TaskFeedback taskFeedback: taskFeedbackList){
            rMap = new HashMap<String, Object>();
            rMap.put("id", taskFeedback.getId());
            rMap.put("feedbackContent", taskFeedback.getFeedbackContent());
            rMap.put("creater", taskFeedback.getCreater()==null?"":taskFeedback.getCreater().getName());
            rMap.put("createDate", taskFeedback.getCreateTime()==null?"": DataUtil.DateToString(taskFeedback.getCreateTime()));
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

}
